package com.alex.controller;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.alex.common.beans.ResultBean;
import com.alex.common.config.IndexConfig;
import com.alex.entity.ArticleEntity;
import com.alex.paramVo.ArticleSearchVo;
import com.alex.service.FilterService;
import com.alex.service.r.Rservice;
import com.alex.service.r.rentity.Conceptualstructuremap;
import com.alex.service.r.rentity.MostObject;
import com.alex.utils.CacheUtil;
import com.alex.utils.CheckUtil;
import com.alex.utils.EsClient;
import com.alex.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.alex.service.AllQueryBasicService.allQuery;
import static java.util.stream.Collectors.toList;


@RestController
@RequestMapping("/rsearch")
@SuppressWarnings(value = "all")
@Slf4j
public class RSearchController {

    private static ElasticsearchClient client = EsClient.client();
    @Resource
    CacheUtil cacheUtil;
    @Resource
    Rservice rservice;
    @Resource
    private FilterService filterService;

    // R 语言画图请求地址
    @GetMapping(value = "rpic")
    public ResultBean<Object> rpic(String uuid, Integer uid) {
        log.info("uuid" + uuid);
        ArticleSearchVo searchVo = (ArticleSearchVo) RedisUtil.getObject(uuid);
        String term = searchVo.getPram();
        BoolQuery.Builder boolQuery = null;
        try {
            boolQuery = filterService.getBoolQuery(searchVo);
        } catch (SQLException | IOException e) {
            e.printStackTrace();
        }
        assert boolQuery != null;
        Query query = boolQuery.build()._toQuery();
        List<String> list = Stream.of("id").collect(Collectors.toList());
        List<Hit<ArticleEntity>> hits = null;
        try {
            hits = allQuery(IndexConfig.CORE_INDEX, query, 0, 300, list, ArticleEntity.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert hits != null;
        List<ArticleEntity> coventList = coventList(hits);
        List<Integer> ids = coventList.stream().map(ArticleEntity::getId).collect(Collectors.toList());
        System.out.println("根据" + uuid);
        System.out.println("获取到的 ids___" + ids.size());
        try {
            log.info("打印部分ids++" + ids.subList(0, 10));
        } catch (Exception e) {

        }
        String uts = rservice.dealUts(ids, term, uid);
        return new ResultBean<>(uts);
    }

    public static <T> List<T> coventList(List<Hit<T>> hits) {
        List<T> collect = hits.stream().map(i -> i.source()).collect(toList());
        return collect;
    }

    @SneakyThrows
    // 获取R语言结果
    @GetMapping("get-r-calculate-res")
    public ResultBean<Object> getSearchWosLocal(String keySearch) {
        Object object = cacheUtil.getObjectByRedis(keySearch);
        if (object == null) {
            CheckUtil.check(false, "错误的查询key");
        }
        Map<Integer, String> msg = new HashMap<>();

        msg.put(1, "进行中");
        msg.put(2, "成功");
        msg.put(3, "失败,请刷新页面");
        msg.put(4, "已过期,请重新刷新页面");
        Integer res = Integer.parseInt(object.toString());
        log.info("结果key+" + keySearch + "++" + res);
        if (res != 2) {
            CheckUtil.check(false, msg.get(res));
        } else {
            Object object1 = cacheUtil.getObjectByRedis(keySearch + "res");
            if (object1 != null) {
                List<String> strings = JSON.parseArray(object1.toString(), String.class);
                return new ResultBean<>(strings);
            }

        }
        return new ResultBean<>();
    }

    //@ApiOperation(value = "testConceptualstructuremap")
    @GetMapping("Conceptualstructuremap")
    public ResultBean<Object> newSearch(String reKey) {
        Object conceptualstructuremaps = rservice.testConceptualstructuremap(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    //@ApiOperation(value = "FactorialMapOfTheDocumentsWithTheHighestContributes")
    @GetMapping("FactorialMapOfTheDocumentsWithTheHighestContributes")
    public ResultBean<Object> newSearch2(String reKey) {
        List<Conceptualstructuremap> conceptualstructuremaps = rservice.FactorialMapOfTheDocumentsWithTheHighestContributes(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    // 新加几个功能测试图
    //@ApiOperation(value = "发文最多国家")
    @GetMapping("MostProdCountriesdf")
    public ResultBean<Object> MostProdCountriesdf(String reKey) {
        List<MostObject> conceptualstructuremaps = rservice.MostProdCountriesdf(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    //@ApiOperation(value = "最多被引次数文章")
    @GetMapping("MostCitedPapersDATA")
    public ResultBean<Object> MostCitedPapersDATA(String reKey) {
        List<MostObject> conceptualstructuremaps = rservice.MostCitedPapersDATA(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    //@ApiOperation(value = "期刊发文最多")
    @GetMapping("MostRelSourcesDATA")
    public ResultBean<Object> MostRelSourcesDATA(String reKey) {
        List<MostObject> conceptualstructuremaps = rservice.MostRelSourcesDATA(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    //@ApiOperation(value = "国家发文被引排行榜")
    @GetMapping("TCperCountries")
    public ResultBean<Object> TCperCountries(String reKey) {
        List<MostObject> conceptualstructuremaps = rservice.TCperCountries(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    //@ApiOperation(value = "年份发文图")
    @GetMapping("yeararticletrendTAB")
    public ResultBean<Object> yeararticletrendTAB(String reKey) {
        List<MostObject> conceptualstructuremaps = rservice.yeararticletrendTAB(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    //@ApiOperation(value = "作者DE关键词发文")
    @GetMapping("AuthorKeywordsDE")
    public ResultBean<Object> AuthorKeywordsDE(String reKey) {
        Object conceptualstructuremaps = rservice.AuthorKeywordsDE(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    //@ApiOperation(value = "ID关键词发文")
    @GetMapping("KeywordsPlusID")
    public ResultBean<Object> KeywordsPlusID(String reKey) {
        Object conceptualstructuremaps = rservice.KeywordsPlusID(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    //@ApiOperation(value = "作者年份发文图")
    @GetMapping("authorProdOverTime")
    public ResultBean<Object> authorProdOverTime(String reKey) {
        Object conceptualstructuremaps = rservice.authorProdOverTime(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }


    //@ApiOperation(value = "期刊发文增长图")
    @GetMapping("sourceGrowth")
    public ResultBean<Object> sourceGrowth(String reKey) {
        Object conceptualstructuremaps = rservice.sourceGrowth(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

//    @ApiOperation(value = "作者合作网络")
//    @GetMapping("AUcollaboration")
//    public ResultBean<Object> AUcollaboration(String reKey) {
//        Object conceptualstructuremaps = rservice.AUcollaboration(reKey);
//        return new ResultBean<>(conceptualstructuremaps);
//    }

    //@ApiOperation(value = "ID关键词发文增长图")
    @GetMapping("idGrowth")
    public ResultBean<Object> idGrowth(String reKey) {
        Object conceptualstructuremaps = rservice.IdGrowth(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }

    //@ApiOperation(value = "获取其他图结果返回map")
    @GetMapping("otherpic")
    public ResultBean<Object> otherpic(String reKey) {
        log.info("rekey++" + reKey);
        Object conceptualstructuremaps = rservice.otherpic(reKey);
        return new ResultBean<>(conceptualstructuremaps);
    }


}
